﻿using System;
using System.Web;
using System.Web.UI.WebControls;
using ASPNETVN.PORTAL.Components.Security;
using ASPNETVN.PORTAL.Components.UI;
using System.Collections;

namespace ASPNETVN.PORTAL.Administration.Module
{
    public partial class CustomPermission : PermissionPage
    {
        protected override void OnInit(EventArgs e)
        {
            this.Update += new EventHandler(CustomPermission_Update);
            this.ButtonUpdate = this.btnUpdate;
            this.ButtonCancel = this.btnCancel;
            base.OnInit(e);
        }

        void CustomPermission_Update(object sender, EventArgs e)
        {
            ArrayList selectedItems = new ArrayList();
            foreach (ListItem item in chkFunction.Items)
            {
                if (item.Selected)
                {
                    selectedItems.Add(item.Value);
                }
            }
            string[] functions = (string[])selectedItems.ToArray(typeof(string));
            PortalSecurity.UpdatePermissions(Convert.ToInt32(ddlRole.SelectedValue), this.ModuleID, functions);

        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack == false)
            {
                // Obtain SiteSettings from Current Context
                PortalDataSet ds = (PortalDataSet)HttpContext.Current.Items["PortalDataSet"];
                PortalDataSet.ModuleRow mRow = ds.Module.FindByID(this.ModuleID);
                int mdID = mRow.ModuleDefinitionID;
                Guid guid = ds.ModuleDefinition.FindByID(mdID).GeneralDefinitionID;
                sdsFunction.SelectParameters["GUID"].DefaultValue = guid.ToString();

                sdsRole.SelectParameters["PortalID"].DefaultValue = Global.PortalID.ToString();
            }
        }

        protected void ddlRole_SelectedIndexChanged(object sender, EventArgs e)
        {
            foreach (ListItem item in chkFunction.Items)
            {
                item.Selected = false;
            }

            string[] roleFunction = PortalSecurity.SelectFunctionBy_RoleID_ModuleID(Convert.ToInt32(ddlRole.SelectedValue), this.ModuleID);
            foreach (ListItem item in chkFunction.Items)
            {
                foreach (string f in roleFunction)
                {
                    if (item.Value == f)
                    {
                        item.Selected = true;
                        break;
                    }
                }
            }
        }
    }
}
